package com.usian.day01.controller;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.usian.common.model.day01.User;
import com.usian.common.utils.JwtUtil;
import com.usian.day01.service.UserService;
import com.usian.common.vo.ResultResopnse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author baimugudu
 * @email 2415621370@qq.com
 * @date 2023/7/25 15:21
 * 请求方式：POST GET PUT DELETE
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    UserService userService;

    /**
     *  @RequestMapping(value = "list",method=RequestMethod.GET)
     * 查询所有list用户  GET
     * @return
     */
    @GetMapping(value = "/list")
    public ResultResopnse list(){
        try{
            List<User> list = userService.list();
            return ResultResopnse.success(list);
        }catch (Exception e){
            return ResultResopnse.error();
        }


    }


    /**
     * 根据ID查询  GET
     * 1:URL 拼接传参：http://localhost:8100/user/findById?id=1  @RequestParam String id
     * 2:restful 风格 占位符:{id} :http://localhost:8100/user/2 @PathVariable String id
     */
    @GetMapping(value = "/{id}")
    public ResultResopnse findById(@PathVariable String id){
        log.info("id:"+id);
        ResultResopnse<User> resultResopnse = new ResultResopnse<>();
        try{
            User user = userService.getById(id);
            resultResopnse.setCode("1");
            resultResopnse.setMessage("查询成功");
            resultResopnse.setData(user);
        }catch(Exception e){
            e.printStackTrace();
            resultResopnse.setCode("2");
            resultResopnse.setMessage("查询失败");
        }

        return resultResopnse;
    }

    /**
     * 根据条件查询：几个查询条件
     *             2个条件  GET http://localhost:8100/user/findByUser?username=12&password=22
     *             大于2个   POST
     */
    @GetMapping(value = "/findByUser")
    public List<User> findByUser(@RequestParam("username") String username,
                                 @RequestParam("password") String password){
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username",username);
        userQueryWrapper.eq("password",password);
        List<User> list = userService.list(userQueryWrapper);
        return list;
    }

    @PostMapping(value = "/findByUser")
    public List<User> findByUser1(@RequestBody User user){
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username",user.getUsername());
        userQueryWrapper.eq("password",user.getPassword());
        List<User> list = userService.list(userQueryWrapper);
        return list;
    }


    /**
     * 添加 POST
     * @return
     */
    @PostMapping("/save")
    public ResultResopnse savUser(@RequestBody User user){
        ResultResopnse resultResopnse = new ResultResopnse();
        try{
            boolean b = userService.save(user);
            resultResopnse.setCode("1");
            resultResopnse.setMessage("添加成功");
            resultResopnse.setData(b);
        }catch(Exception e){
            e.printStackTrace();
            resultResopnse.setCode("2");
            resultResopnse.setMessage("添加失败");

        }
        return resultResopnse;

    }

    /**
     * 修改 POST PUT
     */
    @PutMapping("/update")
    public ResultResopnse update(@RequestBody User user){
        ResultResopnse resultResopnse = new ResultResopnse();
        try{
            boolean b = userService.updateById(user);
            resultResopnse.setCode("1");
            resultResopnse.setMessage("修改成功");
            resultResopnse.setData(b);
        }catch(Exception e){
            e.printStackTrace();
            resultResopnse.setCode("2");
            resultResopnse.setMessage("修改失败");
        }

        return resultResopnse;

    }

    /**
     * 根据ID删除  Delete ,get
     */

    @DeleteMapping("/{id}")
    public ResultResopnse deleteById(@PathVariable String id){
        ResultResopnse resultResopnse = new ResultResopnse();
        try{
            boolean b = userService.removeById(id);
            resultResopnse.setCode("1");
            resultResopnse.setMessage("删除成功");
            resultResopnse.setData(b);
        }catch (Exception e){
            e.printStackTrace();
            resultResopnse.setCode("2");
            resultResopnse.setMessage("删除失败");
        }
       return resultResopnse;

    }

    @Autowired
    RedisTemplate redisTemplate;


    @RequestMapping("/login")
    public ResultResopnse login(@RequestBody User user, HttpSession session){
        log.info(JSON.toJSONString(user));
        //登录成功
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();

        QueryWrapper<User> queryWrapper = userQueryWrapper.eq("username", user.getUsername())
                .eq("password", user.getPassword());

        User user1 = userService.getOne(queryWrapper);
        if(null!=user1){
            //登录成功
            Long id = user1.getId();
            //根据id生成token
            //String token = JwtUtil.getToken(id);
            //对象转成json字符串
            //String userJsonStr = JSON.toJSONString(user1);
            //存到session里面
            //session.setAttribute(token,userJsonStr);
            //redis
           // redisTemplate.opsForValue().set(token,userJsonStr,30,TimeUnit.MINUTES);

            Map map   = new HashMap<>();
            map.put("userId",id);
            String token = JWTUtil.createToken(map, "123".getBytes());
            String userJsonStr = JSON.toJSONString(user1);
            redisTemplate.opsForValue().set(token,userJsonStr,30,TimeUnit.MINUTES);
            return  ResultResopnse.success(token);

        }else {
            return  ResultResopnse.error();
        }


    }

    public static void main(String[] args){
        Map map   = new HashMap<>();
        map.put("userId",100);

       // String token = JWTUtil.createToken(map, "123".getBytes());
       // log.info("token:{}",token);


        String tokenSte=  "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOjEwMH0.v0Ctz78DzkbJLAs6Rthm5GthBu_4ogW5JbJHoSWNPek";
        boolean verify = JWTUtil.verify(tokenSte, "123".getBytes());
        log.info("verify:{}",verify);

        JWT jwt = JWTUtil.parseToken(tokenSte);
        log.info("jwt:{}",JSON.toJSONString(jwt));
        Integer userId = (Integer)jwt.getPayload("userId");
        log.info("userId:{}",userId);


    }




}
